﻿using System.IO;
using System.Net;
using System.Xml.Linq;

namespace BingWallpaper
{
	public static class BingWallpaperHelper
	{
		public static ImageInfo LoadImageInfo()
		{
			var xDoc = XDocument.Load(string.Format("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=0&n=1&mbl=1&mkt=en-ww"));
			if (xDoc.Root == null)
				return null;
			var imageElem = xDoc.Root.Element("image");
			if (imageElem == null)
				return null;
			var urlBaseElem = imageElem.Element("urlBase");
			if (urlBaseElem == null)
				return null;
			var copyrightElem = imageElem.Element("copyright");
			return new ImageInfo(urlBaseElem.Value, copyrightElem == null ? "" : copyrightElem.Value);
		}

		public static Stream LoadImage(string baseUri, int width, int height)
		{
			var data =
				new WebClient().DownloadData(
					string.Format("http://bing.com{0}_{1}x{2}.jpg", baseUri, width, height));
			return new MemoryStream(data);
		}
	}
}